<?php

namespace frontendm\controllers;

use yii\web\Controller;
use Yii;
use yii\helpers\ArrayHelper;
use common\models\User;
use common\components\MTools;
use frontendm\models\WB_UserDrawalRecord;

/* use Yii;
  use frontendm\models\LoginForm;
  use frontendm\models\PasswordResetRequestForm;
  use frontendm\models\ResetPasswordForm;
  use frontendm\models\SignupForm;
  use yii\base\InvalidParamException;
  use yii\web\BadRequestHttpException;
  use yii\web\Controller;
  use yii\filters\VerbFilter;
  use yii\filters\AccessControl; */

/**
 * WeChatController controller
 */
class WechatController extends Controller {

    public $xmlResult;

    public function payment($openid, $money, $userid) {
        //进行转账
        header("Content-type: text/html; charset=utf-8");
        $data['mch_appid'] = 'wx1b30b15c2ba79c2d'; //商户的应用appid
        $data['mchid'] = '1427988602'; //商户ID
        $data['nonce_str'] = $this->unicode(); //$this->unicode();//这个据说是唯一的字符串下面有方法

        $data['partner_trade_no'] = time(); //.time();//这个是订单号。

        $data['openid'] = $openid; //这个是授权用户的openid。。这个必须得是用户授权才能用

        $data['check_name'] = 'NO_CHECK'; //这个是设置是否检测用户真实姓名的

        $data['re_user_name'] = '123'; //用户的真实名字

        $data['amount'] = $money * 100; //提现金额 100为1元

        $data['desc'] = '皓夜科技提现'; //订单描述

        $data['spbill_create_ip'] = $_SERVER['SERVER_ADDR']; //这个最烦了，，还得获取服务器的ip

        $secrect_key = '12345678901234567890123456789012'; ///这个就是个API密码。32位的。。随便MD5一下就可以了

        $data = array_filter($data);

        ksort($data);

        $str = '';

        foreach ($data as $k => $v) {

            $str.=$k . '=' . $v . '&';
        }

        $str.='key=' . $secrect_key;

        $data['sign'] = md5($str);
        $xml = $this->arraytoxml($data);
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

        $res = $this->curl($xml, $url);
        $return = $this->xmltoarray($res);

        if ($return['return_code'] == 'SUCCESS' && $return['result_code'] == 'SUCCESS') {
            $trans = Yii::$app->db->beginTransaction();
            try {
                $userdrawal = WB_UserDrawalRecord::find()->where("userid=:userid", [":userid" => $userid])->one();
                $user = User::findOne($userid);
                if (!$userdrawal instanceof WB_UserDrawalRecord) {
                    //返现推荐账号佣金
                    $refuser = User::find()->where("my_code=:invite_code", [":invite_code" => $user->userprofile->invite_code])->one();
                    if ($refuser instanceof User) {
                        $userpayrecord = new \frontendm\models\WB_UserPayRecordHy();
                        $userpayrecord->userid = $refuser->id;
                        $userpayrecord->type = 1;
                        $userpayrecord->class_type = 1;
                        $userpayrecord->amount = $money * 0.05;
                        $userpayrecord->is_drawal = 1;
                        $userpayrecord->description = "提现返还佣金￥".$money * 0.05;
                        $rebateRecord = new \frontendm\models\WB_UserRebateRecord();
                        $rebateRecord->fuserid = $user->id;
                        $rebateRecord->fusername = $user->username;
                        $rebateRecord->tuserid = $refuser->id;
                        $rebateRecord->tusername = $refuser->username;
                        $rebateRecord->rebate_amount = $money * 0.05;
                        $rebateRecord->amount = $money;
                        if ($userpayrecord->save() && $rebateRecord->save()) {
                            if ($refuser->wallet) {
                                //$refuser->wallet->amount = $refuser->wallet->amount + 1;
                                $refuser->wallet->offline_amount = $refuser->wallet->offline_amount + $money * 0.05;
                                $refuser->wallet->can_drawal_amount = $refuser->wallet->can_drawal_amount + $money * 0.05;
                                $refuser->wallet->save();
                            } else {
                                $useraccount = new \frontendm\models\WB_UserAccountHy();
                                $useraccount->userid = $refuser->id;
                                //$useraccount->amount = 1;
                                $useraccount->offline_amount = $money * 0.05;
                                $useraccount->can_drawal_amount = $money * 0.05;
                                $useraccount->yet_drawal_amount = 0;
                                $useraccount->save();
                            }
                        }
                    }
                }
                $record = new \frontendm\models\WB_UserDrawalRecord();
                $record->partner_trade_no = $return["partner_trade_no"];
                $record->payment_no = $return["payment_no"];
                $record->payment_time = $return["payment_time"];
                $record->amount = $money;
                $record->wxopenid = $openid;
                $record->userid = $userid;
                if ($record->save()) {
                    $user->wallet->can_drawal_amount = $user->wallet->can_drawal_amount - $money;
                    //$user->wallet->amount = $user->wallet->amount - $money;
                    $user->wallet->yet_drawal_amount = $user->wallet->yet_drawal_amount + $money;
                    if ($user->wallet->save()) {
                        $trans->commit();
                        return true;
                    }
                }
            } catch (Exception $ex) {
                $trans->rollBack();
                throw new \yii\web\NotFoundHttpException;
            }
            //申请提现成功
        } else {
            return false;
        }
        // echo getcwd().'/cert/apiclient_cert.pem';die;
    }

    public function xmltoarray($xml) {

        //禁止引用外部xml实体 

        libxml_disable_entity_loader(true);

        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);

        $val = json_decode(json_encode($xmlstring), true);

        return $val;
    }

    public function curl($param = "", $url) {

        $postUrl = $url;

        $curlPost = $param;

        $ch = curl_init();                                      //初始化curl

        curl_setopt($ch, CURLOPT_URL, $postUrl);                 //抓取指定网页

        curl_setopt($ch, CURLOPT_HEADER, 0);                    //设置header

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);            //要求结果为字符串且输出到屏幕上

        curl_setopt($ch, CURLOPT_POST, 1);                      //post提交方式

        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);           // 增加 HTTP Header（头）里的字段 

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);        // 终止从服务端进行验证

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . '/cert/apiclient_cert.pem'); //这个是证书的位置

        curl_setopt($ch, CURLOPT_SSLKEY, getcwd() . '/cert/apiclient_key.pem'); //这个也是证书的位置

        $data = curl_exec($ch);                                 //运行curl

        curl_close($ch);

        return $data;
    }

    public function unicode() {

        $str = uniqid(mt_rand(), 1);

        $str = sha1($str);

        return md5($str);
    }

    public function arraytoxml($data) {

        $str = '<xml>';

        foreach ($data as $k => $v) {

            $str.='<' . $k . '>' . $v . '</' . $k . '>';
        }

        $str.='</xml>';

        return $str;
    }

    /*
     * 微信发送消息的链接地址
     */

    public function actionValid() {
        $wechat = Yii::$app->wechat;
        $this->xmlResult = $wechat->parseRequestXml();
        if ($this->xmlResult) {
            //判断请求的是否为事件
            if (ArrayHelper::getValue($this->xmlResult, "MsgType") == 'event') {
                //判断事件类型
                switch (ArrayHelper::getValue($this->xmlResult, "Event")) {
                    //关注
                    case 'subscribe':
                        $content = "欢迎关注皓夜科技！\n";
                        $content .= "接任务：请点击菜单【平台功能->任务大厅】登陆平台进行接任务！\n";
                        $content .= "新用户注册：请点击菜单【平台功能->注册帐号】进行注册帐号！\n";
                        $content .= "已有帐号请发送bd@帐号@密码 进行公众号绑定。例如：bd@haoye@888888";
                        $this->replayTextMessage($content);
                        break;
                    //点击事件
                    case 'CLICK':
                        $eventKey = ArrayHelper::getValue($this->xmlResult, "EventKey");
                        if ($eventKey == "V1001_TODAY_MUSIC") {//登录
                            $this->loginReplay();
                        } else if ($eventKey == "kefu") { //客服
                            $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                            $this->replayTextMessage($content);
                        } else if ($eventKey == "qrcode") { //二维码
                        } else if ($eventKey == "tixian") {  //提现消息提示
                            $openid = User::find()->where("wxopenid=:wxopenid", [":wxopenid" => ArrayHelper::getValue($this->xmlResult, "FromUserName")])->one();
                            if ($openid instanceof User) {
                                $content = "您目前的可提现金额:" . ($openid->wallet ? Yii::$app->formatter->asDecimal($openid->wallet->can_drawal_amount) : 0) . "，满1元以上才可以提现，可回复格式: TX@金额 进行提现 例如一元: TX@1";
                                $content .= "\n";
                                $content .="------------\n";
                                $content .="为了方便财务 审核，提现以“元”整数为准如有不便，敬请见谅！";
                            } else {
                                $content = "已有账号请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
                            }
                            $this->replayTextMessage($content);
                        } else if ($eventKey == "profile") {
                            $openid = User::find()->where("wxopenid=:wxopenid", [":wxopenid" => ArrayHelper::getValue($this->xmlResult, "FromUserName")])->one();
                            if ($openid instanceof User) {
                                $content = " 用户名：" . $openid->username . "\n";
                                $content .= "帐号余额：" . ($openid->wallet ? $openid->wallet->amount : 0) . " 皓币\n";
                                $content .= " 可提现余额：" . ($openid->wallet ? $openid->wallet->can_drawal_amount : 0) . " 皓币\n";
                                $content .= " 下线奖励：" . ($openid->wallet ? $openid->wallet->offline_amount : 0) . " 皓币\n";
                                $content .= " 任务完成量：" . \frontendm\models\WB_UserTaskOperate::find()->where("userid=:userid and status=1", [":userid" => $openid->id])->count() . "\n";
                                $content .= " 被投诉总量：" . \frontendm\models\WB_UserTaskOperate::find()->where("userid=:userid and status=1 and is_complain !=0", [":userid" => $openid->id])->count() . "\n";
                                $content .= " 邀请小伙伴：" . \frontendm\models\WB_UserProfile::find()->where("invite_code=:invite_code", [":invite_code" => $openid->my_code])->count() . "人" . "\n";
                                $content .= " 您的邀请码：" . $openid->my_code . "\n";
                                $content .= " 您的推广链接：http://www.toupiao518.cn/site/signup.html?id=" . $openid->my_code;
                            } else {
                                $content = "亲，对不起，您还没有绑定账号，无法查询个人信息！已有账号请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
                            }
                            $this->replayTextMessage($content);
                        }
                        break;
                    default:
                        break;
                }
            } else {
                $this->NotEventReplay();
            }
        } else {
            echo "success";
        }
        exit;
    }

    /*
     * 被动回复文本消息
     * @params $content
     */

    private function replayTextMessage($content) {
        $textTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[%s]]></MsgType>
            <Content><![CDATA[%s]]></Content>
            </xml>";
        $resultStr = sprintf($textTpl, ArrayHelper::getValue($this->xmlResult, "FromUserName"), ArrayHelper::getValue($this->xmlResult, "ToUserName"), time(), "text", $content);
        echo $resultStr;
    }

    /*
     * 登录被动回复
     * 
     */

    private function loginReplay() {
        $replayTpl = "<xml>
            <ToUserName><![CDATA[%s]]></ToUserName>
            <FromUserName><![CDATA[%s]]></FromUserName>
            <CreateTime>%s</CreateTime>
            <MsgType><![CDATA[news]]></MsgType>
            <ArticleCount>1</ArticleCount>
            <Articles>
            <item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
            </item>
            </Articles>
            </xml>";
        $title = '登录';
        $desc = '点击登录';
        $picurl = 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1486035377232&di=f34dacfe8302494a298a0375874707a4&imgtype=0&src=http%3A%2F%2Fpic30.nipic.com%2F20130629%2F12319537_151636096347_2.jpg';
        $url = 'http://www.toupiao518.cn/site/index.html?wxopenid=' . ArrayHelper::getValue($this->xmlResult, "FromUserName");
        $resultStr = sprintf($replayTpl, ArrayHelper::getValue($this->xmlResult, "FromUserName"), ArrayHelper::getValue($this->xmlResult, "ToUserName"), time(), $title, $desc, $picurl, $url);
        echo $resultStr;
    }

    /*
     * 被动消息回复，非事件
     * 
     */

    private function NotEventReplay() {
        $replayResult = explode("@", ArrayHelper::getValue($this->xmlResult, "Content"));
        $argcount = count($replayResult);
        if ($argcount == 2) {
            $key = $replayResult[0];
            $value = $replayResult[1];
            if ($key && $value) {
                $user = User::find()->where("wxopenid=:wxopenid", [":wxopenid" => ArrayHelper::getValue($this->xmlResult, "FromUserName")])->one();
                if ($user instanceof User) {
                    if ($user->froststatus == 0) {
                        if ($key == "TX") {
                            $value = (int) $value;
                            if (!is_numeric($value) || !is_int($value) || $value <= 0) {
                                $content = "亲，您输入的金额必须是整数才行呢";
                            } else if ($value < MTools::getYiiParams("rebate_amount")) {
                                $content = "您的帐户金额:" . MTools::getYiiParams("rebate_amount") . "皓币不足以提现。必须满1元以上才可以提现。赶紧去做任务吧~";
                            } else {
                                //判断是否存在金额账户
                                if ($user->wallet) {
                                    if ($value > $user->wallet->can_drawal_amount) {
                                        $content = "亲，对不起提现的金额大于了您的账户余额";
                                    } else {
                                        $res = $this->payment(ArrayHelper::getValue($this->xmlResult, "FromUserName"), $value, $user->id);
                                        if ($res) {
                                            $content = "成功申请提现[".$value."]元。\n\n";
                                            $content .= "系统会在1分钟内将佣金直接转入您的微信零钱账户，同时您会收到微信支付到账通知。";
                                        } else {
                                            $content = "系统繁忙请稍后再试";
                                        }
                                    }
                                } else {
                                    $content = "您的还没有在平台领过任务，不存在金额账户哦，快去领任务提现吧！";
                                }
                            }
                        } else {
                            $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                        }
                    } else if ($user->froststatus == 1) {
                        $content = "亲。您的账号已被冻结，如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                    } else if ($user->froststatus == 2) {
                        $content = "亲。您的账号已被封，如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                    }
                } else {
                    $content = "亲，对不起，您还没有绑定账号，已有账号请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
                }
            } else {
                $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
            }
        } else if ($argcount > 2) {
            $key = "";
            for ($i = 1; $i < $argcount - 1; $i++) {
                $key .=$replayResult[$i] . "@";
            }
            $key = trim($key, "@");
            $bd = $replayResult[0];
            $value = $replayResult[$argcount - 1];
            if ($bd == "bd") {
                if ($key && $value) {
                    $useropen = User::find()->where("wxopenid=:wxopenid and role=2", [":wxopenid" => ArrayHelper::getValue($this->xmlResult, "FromUserName")])->one();
                    if (!$useropen instanceof User) {
                        $user = User::find()->where("username=:username and role=2", [":username" => $key])->one();
                        if ($user instanceof User) {
                            if ($user->validatePassword($value)) {
                                if ($user->wxopenid) {
                                    $content = "您输入的帐号已绑定过了：" . $key;
                                } else {
                                    $user->wxopenid = ArrayHelper::getValue($this->xmlResult, "FromUserName");
                                    if ($user->save()) {
                                        $content = "已经成功为你绑定帐号[".$user->username."]。点击下方菜单，开始体验吧！";
                                    } else {
                                        $content = "对不起，您绑定失败";
                                    }
                                }
                            } else {
                                $content = "对不起，您输入的账号或密码不正确";
                            }
                        } else {
                            $content = "对不起，您输入的账号不存在";
                        }
                    } else {
                        $content = "此微信号已绑定过帐号" . $useropen->username; //"亲。您已经绑定了".."账号。一个微信号只能绑定一个平台账号！";
                    }
                } else {
                    $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
                }
            } else {
                $content = "亲，请发送bd@账号@密码进行公众号绑定。例如:bd@haoye@888888";
            }
        } else {
            $content = "亲。如有问题请加入我们官方群，联系客服能更好的帮您解答。群号：52355521";
        }
        $this->replayTextMessage($content);
    }

    /*
     * 创建菜单
     */

    public function actionCreatemenu() {
        $buttons = [
            [
                'name' => '新的平台公众号',
                'type'=>"media_id",
                'media_id'=>'VeClVW88QI7ZgUAg4B1E0aRmoS7KNUkNHTsIKlju0Iw'
//                'sub_button' => [
//                    [
//                        "type" => "view",
//                        "name" => "注册帐号",
//                        "url" => "http://www.toupiao518.cn/site/signup.html"
//                    ],
//                    [
//                        "type" => "click",
//                        "name" => "任务大厅",
//                        "key" => "V1001_TODAY_MUSIC"
//                    ],
//                    [
//                        "type" => "click",
//                        "name" => "联系客服",
//                        "key" => "kefu"
//                    ]
//                ]
            ],
            [
                'name' => '个人中心',
                'sub_button' => [
                    [
                        "type" => "click",
                        "name" => "申请提现",
                        "key" => "tixian"
                    ],
                    [
                        "type" => "click",
                        "name" => "个人信息",
                        "key" => "profile"
                    ]
                ]
            ]
        ];
        $result = Yii::$app->wechat->createMenu($buttons);
        if ($result) {
            echo "创建菜单成功";
        }
    }
    public function actionGetmaterial(){
        $data = [
            "type"=>"image",
            "count"=>20,
            "offset"=>0
        ];
         $result = Yii::$app->wechat->getMaterialList($data);
         var_dump($result);exit;
                
    }

}
